/*=+--+=#=+--     Unmanned Aerial System Management Software      --+=#=+--+=#*\
|          Copyright (C) 2011 Regents of the University of Colorado.           |
|                             All Rights Reserved.                             |

     This program is free software: you can redistribute it and/or modify
     it under the terms of the GNU General Public License version 2 as
     published by the Free Software Foundation.

     This program is distributed in the hope that it will be useful,
     but WITHOUT ANY WARRANTY; without even the implied warranty of
     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
     GNU General Public License for more details.

     You should have received a copy of the GNU General Public License
     along with this program.  If not, see <http://www.gnu.org/licenses/>.

            Jack Elston                       Cory Dixon                        
|           elstonj@colorado.edu              dixonc@colorado.edu              |
|                                                                              |
\*=+--+=#=+--                 --+=#=+--+=#=+--                    --+=#=+--+=#*/

// File: serialTest.cpp
// Author: Cory Dixon 
// Date: 2/27/01
//
//

#include <unistd.h>
#include <signal.h>
#include <iostream.h>
#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
#include <fcntl.h>

#include "serial.h"
#include "String.h"
#include "type_defs.h"

// functions
void myclose(int value);    // closes open fd and exits
void exitsignal( int signal );
int simpleWrite(const char *dev, const char *baud);
int simpleRead(const char *dev, const char *baud);

#define MAXLINE 256

// global data
SerialPort *serial;
int hexOut = 0;

//----------------------------------------------------------
// Main function
//----------------------------------------------------------

#ifndef VXWORKS
int main(int argc, char *argv[])
{
	// used for getopt to get otions from arguments
	extern int optind;
	//extern char * optarg;
	
	int mode = 0;
	String devStr = "/dev/ttyS0";
	String baudStr = "9600";

	int c;
	while ((c=getopt(argc,argv,"wrh")) != EOF) switch( (char)c)
	   {
		case 'w':
			mode = 0;
			break;
		case 'r':
			mode = 1;
			break;
		case 'h':
			hexOut = 1;
			break;
		default:
			cout << "Unknown arg " << argv[optind - 1] << endl;
			exit(EXIT_SUCCESS);
	}
	if( optind + 2  ==  argc) {
		devStr = String(argv[optind]); 
		baudStr = String(argv[optind + 1]);     
	} else {
		exit(EXIT_SUCCESS);
	}

	// catch signals
	signal( SIGINT, exitsignal);


	if ( mode == 0 ) {
		cout << "simpleWrite\n";
		(void)simpleWrite(devStr.c_str(), baudStr.c_str());
	} else {
		cout << "simpleRead\n";
		(void)simpleRead(devStr.c_str(), baudStr.c_str());
	}
}
#endif
	
int simpleWrite(const char *dev, const char *baud)
{
	String devStr = "/tyCo/2";
	String baudStr = "9600";

	if( dev != NULL )
		devStr = String( dev );
	if( baud != NULL )
		baudStr = String( baud );

	// open serial port
	printf("Openening serial port\n");
	serial = new SerialPort(devStr.c_str(),baudStr.c_str());
	assert(serial != NULL);

	printf("Initializing serial port\n");
	if( serial->init() != SerialPort::Connected ){
		printf("Could not open serial port\n");
		exit(EXIT_FAILURE);
	}
	printf("Opened serial port %s @ %d\n", serial->getDev(), serial->getBaud());

	printf("Sending chararcters\n");
	for(char i=0; i < 127; i++) {
		if( serial->write(&i, 1) != 1 ) 
			perror("serial->write() - error");
	}

	myclose(OK);
	// exit
	return OK;
}


int simpleRead(const char *dev, const char *baud)
{
	String devStr = "/tyCo/2";
	String baudStr = "9600";

	if( dev != NULL )
		devStr = String( dev );
	if( baud != NULL )
		baudStr = String( baud );

	// open serial port
	printf("Openening serial port\n");
	serial = new SerialPort(devStr.c_str(),baudStr.c_str());
	assert(serial != NULL);

	printf("Initializing serial port\n");
	if( serial->init() != SerialPort::Connected ){
		printf("Could not open serial port\n");
		exit(EXIT_FAILURE);
	}
	if( serial->setBlocking() == false )
		perror("serial->setBlocking() - error");
	printf("Opened serial port %s @ %d\n", serial->getDev(), serial->getBaud());

	char buf[256] = { '\0' };
	int rx = 0;
	printf("Waiting for chararcters\n");

	while ( (rx = serial->read(buf, 255)) >= 0 ) 
	{
		printf("Num=%d Val=", rx);
		if( hexOut ) {
			for(int j=0; j < rx; j++)
				printf("0x%x ", buf[j]);
		} else {
			buf[rx] = '\0';
			printf("%s", buf);
		}
		printf("\n");
	}
	perror("serial->read() - error");

	delete serial;
	// exit
	return OK;
}

//----------------------------------------------------------
// close down properly
//----------------------------------------------------------
void myclose(int value)
{
	// close serial
	serial->close();

	// print serialet statistics
	serial->printStats();

	delete serial;

#ifndef VXWORKS
	exit(value);
#endif
}

//----------------------------------------------------------
// catch exit signals
//----------------------------------------------------------
void exitsignal( int signal )
{
	printf("Caught signal %d ... exiting\n",signal);
	fflush(stdout);

	myclose(EXIT_SUCCESS);
}

